package com.chenjim.architecture.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.chenjim.architecture.data.DataStoreHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

interface IState

interface IIntent

abstract class BaseViewModel<S : IState, I : IIntent>(initialState: S) : ViewModel() {

    @Inject
    lateinit var dateStore: DataStoreHelper

    private val _uiState: MutableStateFlow<S> = MutableStateFlow(initialState)
    val uiState = _uiState.asStateFlow()

    fun processIntent(intent: I) {
        viewModelScope.launch(Dispatchers.Default) {
            try {
                handleIntent(intent)
            } catch (e: Exception) {
                onError(e)
            }
        }
    }

    protected abstract suspend fun handleIntent(intent: I)


    protected open fun onError(exception: Exception) {
        // 可以在这里统一处理异常，子类可重写
    }

    protected fun updateUiState(reducer: (S) -> S) {
        _uiState.update { currentState ->
            reducer(currentState)
        }
    }
}